import md5 from 'js-md5';
import { useUserStoreWidthOut } from '@/store/modules/user';
// import { getLoginInfo, getTenantId } from "./auth";

export const getHeaders = (body: any) => {
  const userState = useUserStoreWidthOut();
  const loginInfo = userState.loginInfo;
  const tenantId = userState.tenantId;
  const { ssoUserId: userId, secret } = loginInfo ?? {};
  const headers: any = {
    tenantId,
    userId,
  };

  if (secret) {
    const timestamp = +new Date();
    const onceStr = Math.random().toString(36).substr(2);
    let str = '';
    try {
      str =
        userId +
        tenantId +
        timestamp +
        onceStr +
        secret +
        decodeURIComponent(encodeURIComponent(body));
    } catch (error) {
      str = userId + tenantId + timestamp + onceStr + secret + body;
    }
    const token = md5(str).toLowerCase();
    headers.Authorization = JSON.stringify({
      userId,
      tenantId,
      timestamp,
      onceStr,
      token,
    });
  } else {
    headers.Authorization = '{}';
  }
  return headers;
};

/**
 *  异步处理 无需try-catch
 * @param {Promise} promise
 */
export function handlePromise(promise: any) {
  return promise.then((res: any) => [null, res]).catch((err: any) => [err || 'err', null]);
}

export const findMenuParentId = (menuList: any, menuKey: string) => {
  let topParentId = '';
  let currentId = '';
  let flag = false;
  const handleTree = (list: any, pathname: string, isFirst: boolean) => {
    for (const val of list) {
      if (flag) {
        return;
      }
      if (isFirst) {
        topParentId = val.menuId;
      }
      if (val.menuHref === pathname) {
        flag = true;
        currentId = val.menuId;
        return;
      }
      if (val.children) {
        handleTree(val.children, pathname, false);
      }
    }
  };
  handleTree(menuList, menuKey, true);
  return {
    topParentId: flag ? topParentId : '',
    currentId,
  };
};

// export const uploadInfo = {
//   headers: { Authorization: getHeaders(null).Authorization },
//   action: `${baseURL}/fileService/file/commonUpload`,
// };

export function composeTree<T extends any[]>(list: T, idKey: string, parentKey: string): T {
  if (list.length < 1) {
    return list;
  }
  let data = JSON.parse(JSON.stringify(list)); // 浅拷贝不改变源数据
  let map: any = {};
  const result: any = [];
  data.forEach((item: any) => {
    map[item[idKey]] = item;
  });
  data.forEach((item: any) => {
    const parent = map[item[parentKey]];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  map = {};
  data = [];
  return result;
}

export const flattenTree = <T extends any[]>(list: T, childrenKey = 'children'): T => {
  const data: T = JSON.parse(JSON.stringify(list));
  return data.reduce((pre, cur) => {
    const children = cur[childrenKey] ?? [];
    return pre.concat({ ...cur }, flattenTree(children, childrenKey));
  }, []);
};

export const flattenNodeTree = <T extends any[]>(
  list: T,
  childrenKey = 'children',
  parentId = '-'
): T => {
  const data: T = JSON.parse(JSON.stringify(list));
  return data.reduce((pre, cur) => {
    cur.parentId = parentId ?? '-';
    const children = cur[childrenKey] ?? [];
    return pre.concat({ ...cur }, flattenNodeTree(children, childrenKey, cur.nodeId));
  }, []);
};

export const arrayTreeAddLevel = <T extends any[]>(
  array: T,
  levelName = 'level',
  childrenName = 'children',
  level = 0
): T => {
  const levelValue = level + 1;
  const info: any = array.map((v: any) => {
    v[levelName] = levelValue;
    const child = v[childrenName];
    if (child && child.length) {
      arrayTreeAddLevel(child, levelName, childrenName, levelValue);
    }
    return v;
  });
  return info;
};

export const treeTool = {
  getParentIds(id: any, treeData: any, prop = 'id') {
    const arr: string[] = [];
    const loop = (data: any, IDS: string) => {
      for (let i = 0, length = data.length; i < length; i++) {
        const node = data[i];
        if (node[prop] === IDS) {
          arr.unshift(node[prop]);
          return true;
        } else {
          if (node.children && node.children.length) {
            if (loop(node.children, IDS)) {
              arr.unshift(node[prop]);
              return true;
            }
          }
        }
      }
      return false;
    };
    loop(treeData, id);
    return arr;
  },
  getChildIds(treeData: any, parentId: any, arr?: any) {
    const result: string[] = arr ?? [];
    for (const el of treeData) {
      if (el.parentId === parentId) {
        result.push(el.id);
        if (el.children) {
          this.childNodeDeepWay(el.children, result);
        }
      } else if (el.children) {
        this.getChildIds(el.children, parentId, result);
      }
    }
    return result;
  },
  childNodeDeepWay(treeData: any, arr: any) {
    if (treeData) {
      treeData.forEach((ele: any) => {
        arr.push(ele.id);
        if (ele.children) {
          this.childNodeDeepWay(ele.children, arr);
        }
      });
    }
  },
};

export const isNull = (value: any) => {
  if (value === undefined || value === null || value === '') {
    return true;
  }
  return false;
};
